/*
 * @Author: 15956982113 493885262@qq.com
 * @Date: 2025-05-27 17:00:18
 * @LastEditors: 15956982113 493885262@qq.com
 * @LastEditTime: 2025-05-29 17:46:43
 * @FilePath: \v3-webpack\src\utils\http.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import axios from 'axios'
import { useAuthStore } from '@/store/authStore' // 引入 Pinia store
import CryptoJS from 'crypto-js'
import used from './used';
const service = axios.create({
	baseURL: process.env.VUE_APP_BASE_API,
	timeout: 5000,
})
//加密
// function encryption(config) {
// 	let params = config.params || {};
// 	console.log('加密参数', params)
// 	let keyParams = config.url + config.method + 'd41d8cd98f00b204e9800998ecf8427e'; //固定加密字段
// 	//拼接参数
// 	console.log('加密参数2', Object.keys(params).sort())
// 	let keysSorted = Object.keys(params).sort().map((item) => {
// 		return item + params[item];
// 	}).join('') + keyParams
// 	//加密
// 	// CryptoJS.AES.encrypt(JSON.stringify(data), secretKey).toString()
// }
//处理参数
function handleParams(config) {
	let params = config.params || {};
	params.nowtime = Date.parse(new Date()) / 1000; //精确到秒
	params.version = "1.0.1"; //版本号
	params.sysTypes = "IOS"; //系统
	//加密
	let newParams = used.deepClone(params);
	newParams.url = config.url;
	newParams.method = config.method;
	newParams.key = 'd41d8cd98f00b204e9800998ecf8427e';
	const data = JSON.stringify(used.sortObjectDeep(newParams));//重排
	// const encryptedData = CryptoJS.AES.encrypt(data, 'd41d8cd98f00b204e9800998ecf8427e').toString()
	const encryptedData = CryptoJS.SHA1(newParams).toString(CryptoJS.enc.Hex);//加密
	config.params = params;
	config.params.sign = encryptedData;
	//类型
	if (config.method === 'POST') {
		config.data = params
		delete config.params
	}
	if (config.method === 'GET') {
		config.params = params
	}
}

//请求拦截器
service.interceptors.request.use(
	config => {
		const authStore = useAuthStore()
		if (authStore.token) { // 直接访问 token 状态
			config.headers['X-Token'] = authStore.token
		}
		return config
	},
	error => {
		return Promise.reject(error)
	},
)
//请求响应器
service.interceptors.response.use(
	response => {
		const res = response.data
		if (res.code !== 200) {
			console.log('接口信息报错', res.message)
			// return Promise.reject(new Error(res.message || 'Error'))
		} else {
			return res
		}
	},
	error => {
		console.log('接口信息报错' + error)
		// return Promise.reject(error)
	},
)
/** 不带token的请求	**/
export function httpRequest(config) {
	handleParams(config)
	return service(config)
}
/** 带token的请求 验证token **/
export function httpTokenRequest(config) {
	const authStore = useAuthStore()
	if (authStore.token) { // 直接访问 token 状态
		config.headers['X-Token'] = authStore.token
	} else {
		console.log('token不存在')
	}
	return service(config)
}
export default service